package com.zds.scm.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.zds.scm.common.util.StringUtils;
import com.zds.scm.domain.UserInfo;
/**
 * 用于登陆和字符处理的过滤器
 * @author yhm
 *
 */
public class LoginFilter implements Filter {
	
	private static final Logger	logger			= Logger.getLogger(LoginFilter.class);
	private String encoding="";
	
	public void init(FilterConfig filterConfig) throws ServletException {
		encoding=filterConfig.getInitParameter("Encoding");//读取filter的初始化参数，
		encoding=StringUtils.isNull(encoding)?"UTF-8":encoding;//空值判断
		logger.debug("Filter Init:charEncode="+encoding);
	}
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		logger.debug("doFilter Begin");
		HttpServletRequest request   = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		
		request.setCharacterEncoding(encoding); //设置请求的字符集
		response.setCharacterEncoding(encoding);//设置响应的字符集
		
		String command = request.getParameter("command");//调用登陆Servlet时传递的参数,确定调用其中的Servlet的方法
		if ("login".equals(command)) {         //如果是登陆的页面则不需要过滤处理,直接传递
			chain.doFilter(request, response);
			logger.debug("不拦截所有的登录请求");
		}else {
			logger.debug("拦截所有的非登录请求,做登录和权限判断");
			//1.从会话中得到登陆用户信息
			UserInfo userInfo=(UserInfo)request.getSession().getAttribute("userInfo");
            if(request.getSession().isNew()&&userInfo==null){
            	request.setAttribute("statusCode", 301);
            	request.setAttribute("message", "登陆已经超时");
            	//request.getRequestDispatcher("/loginsub.jsp").forward(request, response);
            	logger.debug("是新的会话");
            	return;
            }
			if(userInfo==null){//3.得不到用户信息或者用户没有权限则跳转到登陆页面或者是会话已经过期
				request.getRequestDispatcher("/").forward(request, response);
				return;
			}else {//2.得到用户信息,判断--用户已经登陆，并且有相应的权限则过滤链继续走
				chain.doFilter(request, response);
			}
		}
		logger.debug("Do Filter End");
	}
	public void destroy() {
		logger.debug("Filter Destroy");
	}
	
}
